package com.lx.jdbc;

import com.lx.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * 事务操作
 */

public class JdbcDemo3 {
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement psmt =null;
        ResultSet rs=null;

        try {
            conn=JDBCUtils.getConnections();
            //开启事务
            conn.setAutoCommit(false);
            String sql = "update student1 set name=? where id = ?";
            psmt=conn.prepareStatement(sql);
            psmt.setString(1,"lixing");
            psmt.setInt(2,1);
            int i = psmt.executeUpdate();
            //提交事务
            conn.commit();
        } catch (SQLException e) {
            //事务回滚
            try {
                if (conn!=null)
                    conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,psmt,conn);
        }
    }
}
